package com.program.facesigninsystem.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.program.facesigninsystem.service.impl.RedisServiceImpl;

import javax.annotation.Resource;

public class TokenUtil {



    /****
     * 默认为10天的token
     * @param uid
     * @param openid
     * @return
     */
    public static String createToken(String uid,String openid){
        String token;
        token= JWT.create().withClaim("uid",uid)
                .withClaim("generatetime",System.currentTimeMillis())
                //设置token过期时间为10天
                .withClaim("exptime", 1000 * 60 * 60 * 24 * 10)
                .sign(Algorithm.HMAC256(openid));
        return token;
    }

    /****
     * 自定义有效时长的token
     * @param uid
     * @param account
     * @param liveTime
     * @return
     */
    public static String createToken(String uid,String account,Long liveTime){
        String token;
        token= JWT.create().withClaim("uid", uid)
                .withClaim("generatetime",System.currentTimeMillis())
                //设置token过期时间为10天
                .withClaim("exptime",liveTime)
                .sign(Algorithm.HMAC256(account));
        return token;
    }

    /****
     * 生成永久有效的Token
     * @param uid
     * @param openid
     * @return
     */
    public static String createPermanentToken(String uid, String openid) {
        return JWT.create()
                .withClaim("uid", uid)
                .withClaim("generatetime", System.currentTimeMillis())
                // 永久有效，不设置过期时间
                .sign(Algorithm.HMAC256(openid));
    }

    /****
     * 返回参数
     * true：toke有效
     * false：token无效
     * @param token
     * @return
     */
    public static boolean decodeToken(String token){
        Long currentTime = System.currentTimeMillis();
        try {
            Long generateTime = JWT.decode(token).getClaim("generatetime").asLong();
            Long expTime = JWT.decode(token).getClaim("exptime").asLong();
            if(currentTime - generateTime > expTime){
                return false;
            }
            else {
                return true;
            }
        }catch (Exception e){
            return false;
        }
    }


    //应该在生成token时将角色id存入token
    public static Integer decodeTokenGetRole(String token){

        try {
            int roleId = JWT.decode(token).getClaim("roleId").asInt();
            return roleId;
        }catch (Exception e){
            return 0;
        }
    }


}
